<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * User_profile
 * @author: Skiychan <dev@skiy.net>
 *
 */

require(APPPATH.'libraries/Mobile_Controller.php');
class User_profile extends Mobile_Controller {
    private $_user_info;
    private $_valid_old_phone_code = "_VALID_OLD_PHONE_CODE";

    public function __construct() {
        parent::__construct();
        $services = array(
            'login_service',
            'user_info_service',
            'user_verify_service'
        );
        $this->load->service($services);
        $this->load->library("form_validation");
        $this->config->load("form_validation");
        $this->_user_info = $this->login_service->get_user_info();
    }

    /**
     * 取得用户信息
     */
    public function user_info_get() {
        $this->login_service->reload_user_info();
        $this->_user_info = $this->login_service->get_user_info();
        //空间
        $user_space = array(
            'used_space' => $this->_user_info['used_space'],
            'capacity' => $this->_user_info['capacity']
        );
        $space = $this->user_info_service->get_format_space_info($user_space);

        //手机号及验证
        $mobile = $this->_user_info['n_mobile'];
        $v_mobile = 0;
        if (! empty($this->_user_info['mobile'])) {
            $mobile = $this->_user_info['mobile'];
            $v_mobile = 1;
        }

        //邮箱及验证
        $email = $this->_user_info['n_email'];
        $v_email = 0;
        if (! empty($this->_user_info['email'])) {
            $email = $this->_user_info['email'];
            $v_email = 1;
        }

        $result = array(
            'uid' => $this->_user_info['id'],
            'name' => $this->_user_info['nickname'],
            'company' => $this->_user_info['company_name'],
            'avatar' => empty($this->_user_info['image']) ? site_url('/static/img/default.gif') : site_url($this->_user_info['image']),
            'mobile' => $mobile,
            'v_mobile' => $v_mobile,
            'email' => $email,
            'v_email' => $v_email,
            'space' => $space
        );

        echo $this->common_response(0, '', array('data' =>$result));
    }

    /**
     * 更新用户信息
     */
    public function user_info_put() {
        //修改公司名
        $company = $this->put('company');
        if (! empty($company)) {
            $data['company_name'] = $company;
        }
        //修改用户名
        $name = $this->put('name');
        if (! empty($name)) {
            $data['nickname'] = $name;
        }

        if (empty($data)) {
            return $this->common_response(1003);
        }
        $update = $this->user_info_service->update_user_info($this->_user_info['id'], $data);
        if ($update === FALSE) {
            return $this->common_response($this->user_info_service);
        } else {
            //批量修改
            foreach ($data as $key => $value) {
                $this->login_service->refresh_user_info($key, $value);
            }
            return $this->common_response(0);
        }
    }

    /**
     * 作废，请使用account_put
     * 新增手机号
     */
    private function mobile_put() {
        //修改手机号
        $mobile = $this->put('mobile');
        $code = $this->put('code');
        if (! empty($mobile) || ! empty($code)) {
            $is_mobile = $this->form_validation->valid_mobile_phone($mobile);
            if ($is_mobile === FALSE) {
                return $this->common_response(1003);
            }
            $check = $this->user_verify_service->check_sms_code($code, $mobile, User_verify_service::PROCESS_VALID_PHONE);
            if ($check === FALSE) {
                return $this->common_response($this->user_verify_service);
            }
            $data['mobile'] = $mobile;
            if (! empty($this->_user_info['n_mobile'])) {
                $data['n_mobile'] = '';
            }
            $update = $this->user_info_service->update_user_info($this->_user_info['id'], $data);
            if ($update === FALSE) {
                return $this->common_response($this->user_info_service);
            }
            return $this->common_response(0);
        }
    }

    /**
     * 退出
     */
    public function logout_get() {
        $this->login_service->logout();
        $this->common_response(0);
    }

    /**
     * 更新头像
     */
    public function avatar_post() {
        $update_image = $this->user_info_service->upload_face($this->_user_info['id'],$this->_user_info['image'], 'avatar');
        if ($update_image === FALSE) {return $this->common_response($this->user_info_service);
        } else {
            $update = $this->user_info_service->update_user_info($this->_user_info['id'], array('image' => $update_image['img']));
            if ($update === FALSE) {
                return $this->common_response($this->user_info_service);
            } else {
                $this->login_service->refresh_user_info('image', $update_image['img']);
                return $this->common_response(0, NULL, array('data' => array('avatar' => site_url($update_image['img']))));
            }
        }
    }

    /**
     * 发送验证码
     * 2首次验证手机 / 3验证旧手机 / 4验证新手机
     * @return array
     */
    public function sms_code_post() {
        $this->form_validation->set_rules('mobile','', 'required|valid_mobile_phone');
        $this->form_validation->set_rules('process', '', 'required');  //进程
        if ($this->form_validation->run() == FALSE) {
            $this->common_response(1003);
        } else {
            $mobile = trim($this->input->post("mobile",TRUE));
            $this->load->service("register_service");
            $check = $this->register_service->check_phone_exists($mobile);
            $process_type = trim($this->input->post("process",TRUE));

            switch ($process_type) {
                case 2:  //验证手机
                    if ($check) {
                        return $this->common_response(5009);
                    } else {
                        $send = $this->user_verify_service->send_sms($mobile, User_verify_service::PROCESS_VALID_PHONE);
                    }
                    break;

                case 3:  //验证旧手机
                    if (! $check) {
                        return $this->common_response(5004);
                    }
                    if ($mobile == $this->login_service->get_user_info('mobile')) {
                        $send = $this->user_verify_service->send_sms($mobile, User_verify_service::PROCESS_VALID_OLD_PHONE);
                    } else {
                        return $this->common_response(1003);
                    }
                    break;

                case 4:  //验证新手机
                    //新旧手机相同
                    if ($mobile == $this->login_service->get_user_info('mobile')) {
                        return $this->common_response(5011);
                    }
                    if ($check) {
                        return $this->common_response(5009);
                    } else {
                        $send = $this->user_verify_service->send_sms($mobile, User_verify_service::PROCESS_MODIFY_PHONE);
                    }
                    break;

                default:
                    return $this->common_response(1003);
            }

            if ($send !== FALSE) {
                return $this->common_response(0);
            } else {
                return $this->common_response($this->user_verify_service);
            }
        }
    }

    /**
     * ::验证邮箱::发送邮箱验证码 account_put结合使用
     */
    public function email_code_post() {
        $this->form_validation->set_rules('email','', 'required|valid_email');
        if ($this->form_validation->run() == FALSE) {
            $this->common_response(1003);
        } else {
            $email = $this->input->post('email', TRUE);
            $check_user = $this->user_verify_service->check_user_by_email($email);
            if (! $this->login_service->is_login()) {
                return $this->common_response(1008);
            }
            if ($check_user) {
                return $this->common_response(5010);
            }
            //如果已经验证过邮箱则不可再次验证
            $get_email = $this->login_service->get_user_info('email');
            if (! empty($get_email)) {
                return $this->common_response(5007);
            }

            $send = $this->user_verify_service->send_email($email, User_verify_service::PROCESS_VALID_EMAIL);
            if ($send === FALSE) {
                return $this->common_response($this->user_verify_service);
            } else {
                return $this->common_response(0);
            }
        }
    }

    /**
     * 验证新建帐号 (手机或邮箱)
     */
    public function account_put() {
        $account = $this->put('account');
        $code = $this->put('code');
        if (! empty($account) || ! empty($code)) {
            $is_mobile = $this->form_validation->valid_mobile_phone($account);
            $is_email = $this->form_validation->valid_email($account);
//            if ($is_mobile || $is_email) {
//                return $this->common_response(1003);
//            }
            if ($is_mobile) {
                $check = $this->user_verify_service->check_sms_code($code, $account, User_verify_service::PROCESS_VALID_PHONE);
                if ($this->check_account_exist($account)) {
                    return $this->common_response(5011);
                }
            } else if ($is_email) {
                //是否已验证邮箱,APP不可更改邮箱
                if (! empty($this->_user_info['email'])) {
                    return $this->common_response(5016);
                }
                $check = $this->user_verify_service->check_email_verify_code($code, $account, User_verify_service::PROCESS_VALID_EMAIL);
                //是否和原邮箱相同
                if ($this->check_account_exist($account, 'email')) {
                    return $this->common_response(5012);
                }
            } else {
                return $this->common_response(1003);
            }
            if ($check === FALSE) {
                return $this->common_response($this->user_verify_service);
            }

            if ($is_mobile) {
                $data['mobile'] = $account;
                if (! empty($this->_user_info['n_mobile'])) {
                    $data['n_mobile'] = '';
                }
            } else {
                $data['email'] = $account;
                if (! empty($this->_user_info['n_email'])) {
                    $data['n_email'] = '';
                }
            }
            $update = $this->user_info_service->update_user_info($this->_user_info['id'], $data);
            if ($update === FALSE) {
                return $this->common_response($this->user_info_service);
            }
            return $this->common_response(0);
        } else {
            return $this->common_response(1003);
        }
    }

    /**
     * 修改密码
     */
    public function password_put() {
        $old_pwd = trim($this->put('password'));
        $new_pwd = trim($this->put('new_password'));
        if ($old_pwd == $new_pwd) {
            return $this->common_response(5017);
        }

        $pwd_valid = $this->form_validation->valid_password($old_pwd);
        $npwd_valid = $this->form_validation->valid_password($new_pwd);
        if (! ($pwd_valid && $npwd_valid)) {
            return $this->common_response(1003);
        }

        $old_uin = $this->login_service->reload_user_info();
        if (md5($old_pwd) !== $old_uin['password']) {
            return $this->common_response(5002);
        }
        $update = $this->user_info_service->update_user_info($this->_user_info['id'], array('password' => md5($new_pwd)));
        if (! $update) {
            return $this->common_response($this->user_info_service);
        } else {
            return $this->common_response(0);
        }
    }

    /**
     * ::修改手机::验证旧手机的验证码
     */
    public function sms_code_check_post() {
        $this->form_validation->set_rules('code','', 'required');
        if ($this->form_validation->run() == FALSE) {
            return $this->common_response(1003);
        } else {
            $code = trim($this->input->post('code',TRUE));
            $mobile = $this->login_service->get_user_info('mobile');
            if (! $mobile) {
                return $this->common_response(1008);
            }
            $check = $this->user_verify_service->check_sms_code($code, $mobile, User_verify_service::PROCESS_VALID_OLD_PHONE, FALSE);
            if ($check === FALSE) {
                return $this->common_response($this->user_verify_service);
            } else {
                $this->session->set_userdata($this->_valid_old_phone_code, $code);
                return $this->common_response(0);
            }
        }
    }

    /**
     * ::修改手机:修改新手机,验证新手机验证码
     */
    public function mobile_new_put() {
        $valid_code = $this->session->userdata($this->_valid_old_phone_code);
        $old_mobile = $this->_user_info['mobile'];
        $mobile = trim($this->put('mobile'));
        $code = trim($this->put('code'));
        if ($old_mobile == $mobile) {
            return $this->common_response(5011);
        }
        $mobile_valid = $this->form_validation->valid_mobile_phone($mobile);
        $old_mobile_valid = $this->form_validation->valid_mobile_phone($old_mobile);
        //检测
        if (($mobile_valid == FALSE)|| ($old_mobile_valid == FALSE) ||
            empty($code) || empty($valid_code)) {
            return $this->common_response(1003);
        }
        //error_log($_SERVER['request_uri'].PHP_EOL."mb:".$mobile." o_mb:".$old_mobile." code:".$code." v_code:".$valid_code.PHP_EOL, 3, "logs/debug.txt");

        $vcheck = $this->user_verify_service->check_sms_code($code, $mobile, User_verify_service::PROCESS_MODIFY_PHONE, TRUE);

        if ($vcheck != FALSE) {
            $check = $this->user_verify_service->check_sms_code($valid_code, $old_mobile, User_verify_service::PROCESS_VALID_OLD_PHONE, TRUE);
            if ($check != FALSE) {
                $update = $this->user_info_service->update_user_info($this->_user_info['id'], array('mobile' => $mobile));
                $this->login_service->reload_user_info();
                if (! $update) {
                    return $this->common_response($this->user_info_service);
                }
                $this->session->unset_userdata($this->_valid_old_phone_code);
                return $this->common_response(0);
            }
        }

        return $this->common_response($this->user_verify_service);
    }

    /**
     * 检查输入的新帐号是否与原帐号相同
     * @param $account
     * @param string $type
     * @return bool|void
     */
    private function check_account_exist($account, $type = 'mobile') {
        if (empty($account)) return $this->common_response(1003);
            if ($type == 'mobile') {
                return $this->_user_info['mobile'] === $account;
            } else if ($type == 'email') {
                return $this->_user_info['email'] === $account;
            }
    }
}
